<?PHP
  class Role{
    public $name = "";
    public $ID   = -1;
    
    public function load($id){
      $id   = $GLOBALS['db']->EscapeString($id);
      $role = $GLOBALS['db']->ReadRow("SELECT name FROM {'dbprefix'}roles WHERE id = '".$id."'");
      if($role){
        $this->name = $role->name;
        $this->ID   = $id;
      }
    }
    
    public static function getAllRoles(){
      if(Cache::contains("roles","all")){
        $res = Cache::getData("roles","all");
      }
      else{
        $roles = $GLOBALS['db']->ReadRows("SELECT id FROM {'dbprefix'}roles ORDER BY name, id");
        foreach($roles as $role){
          $newRole = new Role();
          $newRole->load($role->id);
          $res[] = $newRole;
        }
        Cache::setData("roles","all",$res);
      }
      return $res;
    }
    
    public function canAccess($page){
      $id     = $GLOBALS['db']->EscapeString($this->ID);
      $pageid = $GLOBALS['db']->EscapeString($page->id);
      return $GLOBALS['db']->ReadField("SELECT COUNT(*) FROM {'dbprefix'}role_rights WHERE role = '".$id."' AND page = '".$pageid."'") > 0;
    }
    
    public function clearAccess($page){
      $pageid = $GLOBALS['db']->EscapeString($page->id);
      return $GLOBALS['db']->Execute("DELETE FROM {'dbprefix'}role_rights WHERE page = '".$pageid."'");
    }
    
    public function allowAccess($page){
      return $this->allowAccessByID($page->id);
    }
    
    public function allowAccessByID($pageid){
      $id     = $GLOBALS['db']->EscapeString($this->ID);
      $pageid = $GLOBALS['db']->EscapeString($pageid);
      return $GLOBALS['db']->Execute("INSERT INTO {'dbprefix'}role_rights (role,page) VALUES('".$id."','".$pageid."')");
    }

	public function insert(){
      $name = $GLOBALS['db']->EscapeString($this->name);
      $res =  $GLOBALS['db']->Execute("INSERT INTO {'dbprefix'}roles (name) VALUES('".$name."')");
      Cache::clear("roles");
      Cache::clear("tables","rolelist");
      return $res;
	}

	public function delete(){
      $res = false;
      if($this->ID > 3){
        $id = $GLOBALS['db']->EscapeString($this->ID);
        $res =  $GLOBALS['db']->Execute("DELETE FROM {'dbprefix'}roles WHERE id = '".$id."'");
        if($res) $res = $GLOBALS['db']->Execute("DELETE FROM {'dbprefix'}role_rights WHERE role = '".$id."'");
        if($res) $res = $GLOBALS['db']->Execute("UPDATE {'dbprefix'}user SET role = '1' WHERE role = '".$id."'");
        Cache::clear("roles");
        Cache::clear("tables","rolelist");
      }
      return $res;
	}

  }
?>